﻿@model InvoiceOrderListModel

@using Telerik.Web.Mvc.UI

@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    // var hideProfitReport = false;

    Html.AddScriptParts("~/subsites/Administration/Scripts/jquery.cookie.js");
    //page title
    ViewBag.Title = T("Admin.Invoice").Text;
}

@using (Html.BeginForm("OrderList", "Invoice", FormMethod.Post, new { id = "ordersearch" }))
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/subsites/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.Invoice.Create")
        </div>
        <div class="options">
            <input type="submit" id="generateinvoice-selected" name="generateinvoice-selected" class="t-button" value="@T("Admin.Invoice.Create")" />
        </div>
    </div>
    <input type="hidden" name="start" value="" id="ciStart" />
    <input type="hidden" name="end" value="" id="ciEnd" />
    <input type="hidden" name="selectedIds" value="" id="ciSelected" />

    @Html.HiddenFor(model => model.InvoiceOrderIds)
    @Html.HiddenFor(model => model.OrderKindId)
    <table sstyle="width:100%;">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.TimeZoneId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.TimeZoneId, Model.AvailableTimeZones)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.CustomerEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.CustomerEmail)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("OrderStatusId", Model.AvailableOrderStatuses)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.ShippingStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("ShippingStatusId", Model.AvailableShippingStatuses)
            </td>
        </tr>
        @if (Model.OrderKindId != (int)Nop.Core.Domain.Orders.OrderKind.Commerce)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.PaymentStatusId):
                </td>
                <td class="adminData">
                    @Html.DropDownList("PaymentStatusId", Model.AvailablePaymentStatuses)
                </td>
            </tr>
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.DistrictId):
                </td>
                <td class="adminData">
                    @Html.DropDownListFor(model => model.DistrictId, Model.AvailableDistricts)
                </td>
            </tr>
        }
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderGuid):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.OrderGuid)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.GoDirectlyToNumber)
                <input type="submit" name="go-to-order-by-number" class="t-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>
        @*@if (Model.OrderKindId == (int)Nop.Core.Domain.Orders.OrderKind.Commerce)
            {*@
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchStoreId):
            </td>
            <td class="adminData">
                @(Html.Telerik().ComboBoxFor(model => model.SearchStoreId)
                                .AutoFill(true)
                                .Filterable()
                                .DataBinding(binding => binding.Ajax().Select("StoreList", "Store", new { storeId = Model.SearchStoreId, customerId = 0 })))
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchPaidRefundOrders):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.SearchPaidRefundOrders)
            </td>
        </tr>
        @*}  *@
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchAllOrders):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.SearchAllOrders)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnSearch" class="t-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
    <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<InvoiceOrderModel>()
                        .Name("orders-grid")
                        .ClientEvents(events => events
                            .OnDataBinding("onDataBinding")
                            .OnDataBound("onDataBound")
                            .OnComplete("onComplete"))
                        .Columns(columns =>
                        {
                            columns.Bound(x => x.Id)
                            .ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
                            .Title("<input id='mastercheckbox' type='checkbox'/>")
                            .Width(50)
                            .HtmlAttributes(new { style = "text-align:center" })
                            .HeaderHtmlAttributes(new { style = "text-align:center" });

                            columns.Bound(x => x.Id);
                            columns.Bound(x => x.OrderStatus);
                            columns.Bound(x => x.PaymentStatus);
                            columns.Bound(x => x.ShippingStatus);
                            columns.Bound(x => x.CustomerEmail);
                            columns.Bound(x => x.CreatedOn).ClientTemplate("<#= CreatedOnStr #>");
                            columns.Bound(x => x.OrderTotal)
                                 .FooterTemplate(
                                 string.Format("<div><strong>{0}:</strong></div>" +
                                //(hideProfitReport ? "{1}" : "<div>{1}: <span id=\"aggregator-profit-block\"></span></div>") +
                                 "<div>{1}: <span id=\"aggregator-subtotal-block\"></span></div>" +
                                 "<div>{2}: <span id=\"aggregator-fuelsurcharge-block\"></span></div>" +
                                 "<div>{3}: <span id=\"aggregator-tax-block\"></span></div>" +
                                 "<div>{4}: <span id=\"aggregator-total-block\"></span></div>",
                                 @T("Admin.Orders.Report.Summary").Text,
                                 @T("Admin.Orders.Report.SubtotalExclTax").Text,
                                 @T("Admin.Orders.Report.FuelSurcharge").Text,
                                //(hideProfitReport ? "" : @T("Admin.Orders.Report.Profit").Text),
                                 @T("Admin.Orders.Report.Tax").Text,
                                 @T("Admin.Orders.Report.Total").Text));
                            columns.Bound(x => x.Id)
                                .Template(x => Html.ActionLink(T("Admin.Common.View").Text, "Edit", new { id = x.Id }))
                                .ClientTemplate("<a href=\"/Admin/Order/Edit/<#= Id #>\">" + T("Admin.Common.View").Text + "</a>")
                                .Width(50)
                                .Centered()
                                .Title(T("Admin.Common.View").Text);
                        })
                        .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                        .DataBinding(dataBinding => dataBinding.Ajax().Select("_OrderList", "Invoice", Model))
                        .EnableCustomBinding(true))
            </td>
        </tr>
    </table>

    <script type="text/javascript">

        var selectedIds = [];
        var reportAggregates = "";
        var cookieKey = "spotshub.invoice.ordersearch";
        function saveCookie() {
            var form = $('#ordersearch');
            if (form) {
                str = form.serialize();
                $.cookie(cookieKey, str, { expires: 2 });
            }
        };

        function restoreCookie() {
            var form = $('#ordersearch');
            if (form) {
                str = $.cookie(cookieKey);
                if (str) {
                    data = str.split('&');
                    $(data).each(function () {
                        nameValue = this.split('=');
                        var name = nameValue[0];
                        //Billing Email and orderkindId does not need to be captured
                        if (name != 'CustomerEmail' && name != 'OrderKindId') {
                            //Timezone value change from "a+b+c" to "a b c"
                            var value = nameValue[1].replace(/\+/g, " ");
                            value = decodeURIComponent(value);
                            form.find('[name="' + name + '"]').val(value);
                        }
                    });
                }
            }
        };

        $(document).ready(function () {
            restoreCookie();
            //search button
            $('#btnSearch').click(function (e) {
                //Remove old search cookie
                e.preventDefault();

                //Remove the old cookie and update to the current form values
                saveCookie();

                //search
                var grid = $('#orders-grid').data('tGrid');
                grid.currentPage = 1; //new search. Set page size to 1
                grid.ajaxRequest();
                //clear selected checkboxes
                $('.checkboxGroups').attr('checked', false).change();
                selectedIds = [];
                return false;
            });

            //"Generate invoice" button
            $('#generateinvoice-selected').click(function (e) {
                //e.preventDefault();
                //redirect to required URL
                var start = $('#@Html.FieldIdFor(model => model.StartDate)').val();
                var end = $('#@Html.FieldIdFor(model => model.EndDate)').val();
                $("#ciStart").val(start);
                $("#ciEnd").val(end);
                $("#ciSelected").val(selectedIds.join(","));

                //check OrderId begin
                var selectChecked = [];
                $("input[name=checkedRecords]").each(function () {
                    var isChecked = $(this).is(":checked");
                    if (isChecked) {
                        var thisObj = $(this).parent().parent().find("td").eq(5).text();
                        selectChecked.push(thisObj);
                    }
                });
                if (selectChecked.length === 0) {
                    alert("Please choose an order!");
                    return false;
                } else {
                    for (var i = 0; i < selectChecked.length; i++) {
                        var selectValue = selectChecked[i];
                        for (var j = 0; j < selectChecked.length; j++) {
                            if (selectChecked[i] !== selectChecked[j]) {
                                alert("The selected orders belong to different shopper, please choose it carefully!");
                                return false;
                            }
                        }
                    }
                }
                //check OrderId end
                return true;
            });

            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes.
            $('#orders-grid input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });
        });

        function onDataBinding(e) {
            var searchModel = {
                StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                CustomerEmail: $('#@Html.FieldIdFor(model => model.CustomerEmail)').val(),
                OrderStatusId: $('#@Html.FieldIdFor(model => model.OrderStatusId)').val(),
                PaymentStatusId: $('#@Html.FieldIdFor(model => model.PaymentStatusId)').val(),
                ShippingStatusId: $('#@Html.FieldIdFor(model => model.ShippingStatusId)').val(),
                OrderGuid: $('#@Html.FieldIdFor(model => model.OrderGuid)').val(),
                InvoiceOrderIds: $('#@Html.FieldIdFor(model => model.InvoiceOrderIds)').val(),
                DistrictId: $('#@Html.FieldIdFor(model => model.DistrictId)').val(),
                TimeZoneId: $('#@Html.FieldIdFor(model => model.TimeZoneId)').val(),
                SearchAllOrders: $('#@Html.FieldIdFor(model => model.SearchAllOrders)').is(':checked'),
                SearchStoreId: $('#SearchStoreId').val(),
                SearchPaidRefundOrders: $('#@Html.FieldIdFor(model => model.SearchPaidRefundOrders)').is(':checked')
            };
            e.data = searchModel;
        }

        function onDataBound(e) {

            $('#orders-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.
                $(this).attr('checked', checked > -1);
            });

            updateMasterCheckbox();

            reportLoaded(e);
        }

        function onComplete(e) {
            var result = e.response;
            if (result) {
                reportAggregates = e.response["aggregates"];
            }
        }

        function reportLoaded(e) {
            if (reportAggregates != "") {
                updateAggregates(reportAggregates);
            }
        }
        function updateAggregates(aggs) {
            for (var key in aggs) {

                @*@if (!hideProfitReport)
                {
                <text>$('#aggregator-profit-block').text(aggs['aggregatorprofit']);</text>
                }*@
                $('#aggregator-subtotal-block').text(aggs['aggregatorsubtotalexcltax']);
                $('#aggregator-fuelsurcharge-block').text(aggs['aggregatorfuelsurcharge']);
                $('#aggregator-tax-block').text(aggs['aggregatortax']);
                $('#aggregator-total-block').text(aggs['aggregatortotal']);
            }
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#orders-grid input[type=checkbox][id!=mastercheckbox]').length;
            var numChkBoxesChecked = $('#orders-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
            $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }
    </script>

}